package com.hy.frame.recycler;

import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * title BaseHolder for RecyclerView
 * author HeYan
 * time 2020/11/30 13:34
 * desc 1. 默认根布局宽度MATCH_PARENT
 * 2. findViewById(int id)中增加了缓存机制
 */
public class BaseHolder extends RecyclerView.ViewHolder {
    private final View mLayout;
    private SparseArray<View> views;

    public BaseHolder(@NonNull View mLayout) {
        this(mLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    public BaseHolder(@NonNull View mLayout, int width, int height) {
        super(mLayout);
        if (mLayout.getLayoutParams() == null) {
            mLayout.setLayoutParams(new ViewGroup.LayoutParams(width, height));
        }
        this.mLayout = mLayout;
    }

    private void addCacheView(int id, View v) {
        if (views == null) {
            views = new SparseArray<>();
        }
        if (v == null) {
            views.remove(id);
        } else {
            views.put(id, v);
        }
    }

    private View findCacheView(int id) {
        if (views != null) {
            return views.get(id);
        }
        return null;
    }


    /**
     * 获取 控件
     *
     * @param id 布局中某个组件的id
     */
    @SuppressWarnings("unchecked")
    public <V extends View> V findViewById(int id) {
        View v = findCacheView(id);
        if (v == null) {
            v = mLayout.findViewById(id);
            addCacheView(id, v);
        }
        if (v != null) {
            return (V) v;
        }
        return null;
    }


    /**
     * 获取 控件
     *
     * @param id     布局中某个组件的id
     * @param parent parent
     */
    public <V extends View> V findViewById(int id, View parent) {
        if (parent != null) {
            return parent.findViewById(id);
        }
        return findViewById(id);
    }
}
